package com.example.famhealing.timeline;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import com.example.famhealing.R;
import com.example.famhealing.schedule.CalendarMonthAdapter;
import com.example.famhealing.schedule.CalendarPopup;

public class TimelineActivity extends Activity implements OnClickListener{

	EditText dayText;

	ImageButton setDate;

	int curYear;
	int curMonth;
	int curDay;

	int year;
	int month;
	int day;

	String sDay;

	public static String searchDate = "";

	private ArrayList<Condition_List_Data> Array_Data;
	private Condition_List_Data data;
	private ConditionListAdapter adapter;

	String time = "";
	String condition = "";
	String sideEffects = "";
	String weight = "";
	String temper = "";
	String heart = "";
	String pressure = "";
	String medicine = "";
	String memo = "";
	// 다이어리 작성자
	String memowriter = "";
	String condwriter = "";
	String wt = "";
	String ph = "";

	ListView condition_list;

	String diaryUrl = "http://192.168.0.61:8080/famhealing/getSchedule.get?phone_num=01011111111";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_timeline);

		dayText = (EditText) findViewById(R.id.dayText);

		GregorianCalendar cal = new GregorianCalendar();

		sDay = getDay(cal);

		setDayText(TimelineActivity_.selectedYear,
				TimelineActivity_.selectedMonth, TimelineActivity_.selectedDay,
				sDay);

		setDate = (ImageButton) findViewById(R.id.setDate);
		setDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				// 날짜 하나만 선택 가능하도록
				CalendarMonthAdapter.multiSelect = false;

				// 타임라인 날짜 검색 위한 팝업창(달력) 띄우기
				Intent intent = new Intent(getBaseContext(),
						CalendarPopup.class);
				startActivityForResult(intent, 0);
			}

		});
		Array_Data = parsingData();

		condition_list = (ListView) findViewById(R.id.condition_List);
		adapter = new ConditionListAdapter(this,
				android.R.layout.simple_list_item_1, Array_Data);
		condition_list.setAdapter(adapter);
		
		ImageButton scrapButton=(ImageButton)findViewById(R.id.timeline_scrap);
		ImageButton healingButton=(ImageButton)findViewById(R.id.timeline_healing);
		scrapButton.setOnClickListener(this);
		healingButton.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.timeline, menu);
		return true;
	}

	private String getDay(GregorianCalendar calendar) {

		switch (calendar.get(Calendar.DAY_OF_WEEK)) {
		case 1:
			sDay = "일";
			break;
		case 2:
			sDay = "월";
			break;
		case 3:
			sDay = "화";
			break;
		case 4:
			sDay = "수";
			break;
		case 5:
			sDay = "목";
			break;
		case 6:
			sDay = "금";
			break;
		case 7:
			sDay = "토";
			break;
		}
		return sDay;
	}

	private void setDayText(int year, int month, int date, String day) {

		if (month < 10) {
			if (date < 10) {
				dayText.setText(year + ".0" + month + ".0" + date + "(" + day
						+ ")");
			} else {
				dayText.setText(year + ".0" + month + "." + date + "(" + day
						+ ")");
			}
		} else {
			if (date < 10) {
				dayText.setText(year + "." + month + ".0" + date + "(" + sDay
						+ ")");
			} else {
				dayText.setText(year + "." + month + "." + date + "(" + sDay
						+ ")");
			}
		}
	}

	public ArrayList<Condition_List_Data> parsingData() {
		ArrayList<Condition_List_Data> Array_Data = new ArrayList<Condition_List_Data>();
		String temp = "";

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.permitNetwork().build());

		try {
			URL url1 = new URL(diaryUrl);
			InputStream in = url1.openStream();

			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser parser = factory.newPullParser();

			parser.setInput(in, "euc-kr");

			int eventType = parser.getEventType();
			boolean isItemTag = false;
			String tagName = "";
			boolean check = false;

			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					tagName = parser.getName();
					if (!tagName.equals("data") && !tagName.equals("diary"))
						isItemTag = true;
				} else if (eventType == XmlPullParser.TEXT && isItemTag == true) {
					if (tagName.equals("time")) {
						time = parser.getText();
					}
					if (tagName.equals("cond")) {
						condition = parser.getText();
					}
					if (tagName.equals("side_effects")) {
						temp = parser.getText();
						if (temp.equals("null")) {
							eventType = parser.next();
							continue;
						}

						sideEffects = getConditionString(temp);
					}
					if (tagName.equals("weight")) {
						weight = parser.getText() + "kg";
					}
					if (tagName.equals("temper")) {
						temper = parser.getText() + "ºC";
					}
					if (tagName.equals("heart_rate")) {
						heart = parser.getText() + "bpm";
					}
					if (tagName.equals("pressure")) {
						pressure = parser.getText() + "mmHg";
					}
					if (tagName.equals("memo")) {
						memo = parser.getText();
					}
					if (tagName.equals("memowriter")) {
						memowriter = parser.getText();
					}
					if (tagName.equals("condwriter")) {
						condwriter = parser.getText();
					}
					if (tagName.equals("weight_temper")) {
						wt = parser.getText();
					}
					if (tagName.equals("pressure_heartrate")) {
						ph = parser.getText();
					}
				} else if (eventType == XmlPullParser.END_TAG) {
					isItemTag = false;
					if (tagName.equals("diagnose_check") && check == false) {
						data = new Condition_List_Data(condition, sideEffects,
								weight, temper, heart, pressure, medicine,
								memo, time);
						Array_Data.add(data);
						check = true;
					} else if (!tagName.equals("diagnose_check")
							&& check == true)
						check = false;
				}

				eventType = parser.next();
			}
		} catch (Exception e) {
			System.out.println(e);
		}

		return Array_Data;
	}

	public String getConditionString(String temp) {
		String result = "";
		for (int i = 0; i < 19; i++) {
			if (temp.split("/")[i].equals("1")) {
				switch (i) {
				case 0:
					result += "구역, 구토\n";
					break;
				case 1:
					result += "설사, 복통\n";
					break;
				case 2:
					result += "두통\n";
					break;
				case 3:
					result += "어지러움, 환각증세\n";
					break;
				case 4:
					result += "변비\n";
					break;
				case 5:
					result += "가슴통증\n";
					break;
				case 6:
					result += "출혈, 멍\n";
					break;
				case 7:
					result += "대소변이 검거나 붉은색\n";
					break;
				case 8:
					result += "관절통, 근육통\n";
					break;
				case 9:
					result += "부종, 얼굴이 붓는다\n";
					break;
				case 10:
					result += "경련, 발작\n";
					break;
				case 11:
					result += "불면증\n";
					break;
				case 12:
					result += "탈수증\n";
					break;
				case 13:
					result += "호흡곤란\n";
					break;
				case 14:
					result += "고열\n";
					break;
				case 15:
					result += "발한\n";
					break;
				case 16:
					result += "손발저림, 따끔거림, 감각이상\n";
					break;
				case 17:
					result += "두드러기, 피부 과민반응\n";
					break;
				case 18:
					result += "눈물, 눈부심\n";
					break;
				}
			}
		}
		return result;
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Integer year = 0, month = 0, date = 0;
		String day = "";
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == 0) {
			String yearstr = "";
			String monthstr = "";
			String datestr = "";

			year = Integer.parseInt(data.getStringExtra("curYear"));
			month = Integer.parseInt(data.getStringExtra("curMonth"));
			date = Integer.parseInt(data.getStringExtra("curDay"));

			GregorianCalendar d = new GregorianCalendar(year, month - 1, date,
					0, 0);

			day = getDay(d);
			setDayText(year, month, date, day);

			yearstr = String.valueOf(year);
			if (month < 10)
				monthstr += "0" + String.valueOf(month);
			else
				monthstr = String.valueOf(month);
			if (date < 10)
				datestr += "0" + String.valueOf(date);
			else
				datestr = String.valueOf(date);

			diaryUrl = "http://192.168.0.61:8080/famhealing/getReport.get?phone_num=01011111111&date="
					+ yearstr + monthstr + datestr;
			Array_Data = parsingData();

			adapter = new ConditionListAdapter(this,
					android.R.layout.simple_list_item_1, Array_Data);
			condition_list.setAdapter(adapter);
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch(v.getId())
		{
		case R.id.timeline_scrap:
			intent=new Intent(getBaseContext(), ScrapTimelineActivity.class);
			startActivity(intent);
			overridePendingTransition(0,0);
			finish();
			break;
		case R.id.timeline_healing:
			intent=new Intent(getBaseContext(), HealingTimelineActivity.class);
			startActivity(intent);
			overridePendingTransition(0,0);
			finish();
			break;
		}
	}

}
